package com.wb.utils

import com.wb.component.Slf4j.Companion.log
import com.wb.utils.encryption.Md5Encryption
import com.gargoylesoftware.htmlunit.BrowserVersion
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController
import com.gargoylesoftware.htmlunit.Page
import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.html.HtmlPage
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.net.URLEncoder
import java.nio.charset.Charset
import java.time.LocalDateTime
import java.util.*

/**
 * c酱工具类（调用/爬取c酱表情包网站内容）
 *
 * @author 祁雪
 */
class DbbqbCom {

    companion object {

        val URL_MAP = mapOf(
            // 搜索表情包 - w.搜索词 start.开始位置 默认0
            "search" to "https://www.dbbqb.com/api/search/json",
            "pageSearch" to "https://www.dbbqb.com/s"
        )

        fun getWebKey(): Array<String> {

            val chars = "0a1b2c3d45e67f89";

            var s = "";
            for (i in 0 until 8) {
                s += chars[(Math.random() * chars.length).toInt()];
            }

            val date = LocalDateTime.now()

            val y = date.year

            val m = if (date.monthValue < 10) {
                "0${date.monthValue}"
            } else date.monthValue

            val d = if (date.dayOfMonth < 10) {
                "0${date.dayOfMonth}"
            } else date.dayOfMonth

            val h = if (date.hour < 10) {
                "0${date.hour}"
            } else date.hour

            val min = if (date.minute < 10) {
                "0${date.minute}"
            } else date.minute

            val a = "$s$y$d$m$h$min"

            val str = Md5Encryption.encode(a)
//            println("${Md5Encryption.encode(str)}${str}")
            val keys = arrayOf(str.substring(0, s.length), str.substring(s.length) + s)

            return keys
        }

        fun searchWeb(key: String): List<String> {

//            val search = URLEncoder.encode(key, Charset.defaultCharset())
            try {
//                println(page)
                val keys = getWebKey()
                val result = RestUtil.sendGet(
                    URL_MAP.get("search")!!, hashMapOf(
                        "w" to key,
                        "start" to "0"
                    ),
                    hashMapOf(
                        "Web-Agent" to "web",
                        keys[0] to keys[1]
                    )
                )
                println(result)
                // 解析
                val list = Gson().fromJson(
                    result,
                    object : TypeToken<List<HashMap<String, Any>>>() {}.type
                ) as List<HashMap<String, Any>>

                return list.map { "https://image.dbbqb.com/${it.get("path")}" }

            } catch (e: Exception) {
                log.error("搜索表情包失败", e);
            }

            return emptyList();
        }

    }

}

fun main() {
    val list = DbbqbCom.searchWeb("小黄鸡")
    println(list.get(0))
    val url = list.get(0)
    val fileName = url.substring(url.lastIndexOf("/") + 1)
    FileNetUtil.downHttpUrl(url, "C:\\Users\\76167\\Desktop\\文档数据\\test", fileName)
}